//app.js
var util = require('/util/util.js');
const qiniuUploader = require("/util/qiniuUploader");
App({
  data:{
    
   'apiHost': 'http://www.tenement.com:81/',
    'apiHost': 'https://www.bestsmartbee.com/',
    'mockUrl':'http://www.apidoc.com/mock2?uri=',
    'qiniuUrl':'http://oi7jj3s01.bkt.clouddn.com/',
    'websocket': 'wss://www.boxphp.me',
    //'websocket': 'ws://127.0.0.1:9501',
    'mock': 0,//全局使用mock请求 
    debug:1,
    wxapp:"",
    socketOpen:false,
    socketMsgQueue:[],
    socketRevQueue:{},
    getUserInfoCb:[],
  },
  pageData:{},
  util: util,
  window:function(){
     //console.log("window");
     var _this=this;
      wx.getSystemInfo({complete:function(res){
          _this.globalData.window=res;
          _this.globalData.window.rpx=750/res.windowWidth;
      }})
  },
  getShopInfo(){
    var extConfigSync = this.getExtConfigSync();
    var shop_info = wx.getStorageSync("shop_info");
    if (!shop_info) {
      shop_info = extConfigSync.shop_list[0];
      wx.getStorageSync("shop_info", shop_info);
    }
    return shop_info;
  },
  getLocation:function(cb){
    var that = this
    if (this.globalData.userLocation) {
      typeof cb == "function" && cb(this.globalData.userLocation)
    } else {
      wx.getLocation({
        type: 'gcj02', //返回可以用于wx.openLocation的经纬度
        success: function (res) {
          //  console.log(res);
            that.globalData.userLocation = res;
            typeof cb == "function" && cb(that.globalData.userLocation);
        }
      })
    }
  },
  //
  runGetUserInfoCb:function(userInfo){
    for (var i in this.data.getUserInfoCb){
      var fun = this.data.getUserInfoCb[i];
      typeof fun == "function" && fun(userInfo);
    }
    this.data.getUserInfoCb=[];
  },

  loginByUserInfo: function (userInfo, cb) {
    // console.log(userInfo);
    var that = this;
    //调用登录接口
    wx.login({
      fail: function (res) {
        console.log(res);
      },
      success: function (loginRes) {
        // console.log("loginRes", loginRes);
        userInfo.method = "POST";
        userInfo.code = loginRes.code;
        userInfo.wxapp = that.data.wxapp;
        userInfo.fields = "user_id,store_id,phone,nickname,phone,avatarUrl,last_update_time";
        userInfo.rawData = JSON.stringify(userInfo.userInfo);
        that.api("/api/user/loginByWxApp", userInfo, function (userRes) {
          console.log("userRes", userRes);
          // if (userRes.code == 3 || !userRes.data.phone) {
          //   wx.navigateTo({
          //     url: '/pages/user/bindphone?page=bindphone',
          //   })
          //   return false;
          // }
          if (userRes.code != 200 && userRes.code != 3) {
            that.alert(userRes.msg);
            return false;
          }
          // console.log(userRes);
          that.globalData.userInfo = userRes.data
          that.runGetUserInfoCb(that.globalData.userInfo);
          typeof cb == "function" ? cb(userRes) : '';
        });
      }
    })
  },

  getUserInfo: function (cb) {
   // console.log(this.data.getUserInfoCb.length);
    var that = this
    this.data.getUserInfoCb.push(cb);
    if (this.data.getUserInfoCb.length > 1) {
      return;
    }
    var user_info = this.globalData.userInfo;
    console.log(user_info);
    if (user_info) {
      this.runGetUserInfoCb(user_info);
      //typeof cb == "function" && cb(this.globalData.userInfo)
    } else {
      console.log("getSetting");
      wx.getSetting({
        complete: function (res){
          if (res.errMsg !="getSetting:ok"){
            that.alert(res.errMsg);
          }
          console.log("getSetting complete", res);
        },
        success: function (res) {
          console.log("getSetting success");
          console.log(res);
          console.log(res.authSetting['scope.userInfo']);
          if (res.authSetting['scope.userInfo']) {
            // 已经授权，可以直接调用 getUserInfo 获取头像昵称
            wx.getUserInfo({
              success: function (res) {
                console.log(res);
                that.loginByUserInfo(res);
              },
              fail: function (res) {
                that.alert('授权失败!');
              },
              complete: function (res) {
                console.log("getUserInfo complete", res);
              }
            })

          } else if (!res.authSetting['scope.userInfo']) {
            console.log("redirectTo ", "/pages/user/bindphone?page=auth");
           // that.alert("/pages/user/bindphone?page=auth");
            wx.reLaunch({
              url: '/pages/user/bindphone?page=auth',
              complete:function(res){
                console.log(res);
              }
            })
          }
        }
      })

    }
  },
  globalData:{
    userInfo:null,
    window:{}
  },
  onShow: function() {
    console.log("onshow");
    var that = this;
    // wx.onUserCaptureScreen(function (res) {
    //   that.alert("用户截屏了");
    // })
      // Do something when show.
  },
  onHide: function() {
     console.log("onHide");
      // Do something when hide.
  },
  getExtConfigSync:function(){
    let extConfig = wx.getExtConfigSync ? wx.getExtConfigSync() : {}
    if (!extConfig.theme){
      extConfig.theme ="pages_black";
    }
    return extConfig;
  },
  getUrl:function(url,data){
    var params = this.requestParam(url,data);
    var json = params.param;
    var arg = Object.keys(json).map(function (key) {
      return encodeURIComponent(key) + "=" + encodeURIComponent(json[key]);
    }).join("&");
    console.log(params.url + "?" + arg);
    return params.url + "?" + arg +"#wechat_redirect";
  },
  //请求接口
 requestParam:function(url,data,cb){
   var host=this.data.apiHost; 
   if (url.indexOf("http")!==0){
      url = host + url;
   }
   var param={};
   var cbf=cb;
   if(typeof(data)=='function'){
     cbf=data; 
   }else if(typeof(data)=='object'){
    param=data;
   }
   this.data.debug == 1 ? param['time'] = Date.parse(new Date()) :'';

   var extConfig = this.getExtConfigSync();
  //  console.log("extConfig", extConfig);
   param['from_wx_app']=1;
   param['store_id'] = extConfig.store_id ? extConfig.store_id:'140';
   param['appid'] = extConfig.appid ? extConfig.appid : 'wxb6038a87fc6eae45';
   
   //param['uuid']='wx101';
   var user_info = this.globalData.userInfo && this.globalData.userInfo.token ? this.globalData.userInfo : wx.getStorageSync("user_info");

   param['token'] = user_info ? user_info.token:'';
   param['runThreadKey']='eee50acd6ee441d75ad2b87c9747d09b'; 
   console.log("param:", param);
   return {
     'param':param,
     'url':url,
     'cb':cbf,
   };
 },

 

 api:function(url,data={},cb){
   if (url.indexOf("http") === 0) {
     var apiUrl = url;
   } else {
     var apiUrl = this.data.apiHost + url;
   }
   //console.log(this.data.mock);
   if (data['mock']==1 || this.data.mock ==1){
     apiUrl = this.data.mockUrl+url;
   }
   if (data['mock'] == 0 ){
     apiUrl = this.data.apiHost+url;
   }

   this.postData(apiUrl,data,cb);
 },

 postData:function(url,data,cb){
  //  wx.showToast({
  //    title: '加载中...',
  //    icon: 'loading',
  //    duration: 5000
  //  });
   wx.showNavigationBarLoading();
   var p=this.requestParam(url,data,cb);
   console.log("postData:", p);
   var method = p['param']['method'] ? p['param']['method'] :'GET';
  // console.log("postData:");
   
   var cbf=p['cb'];
   wx.request({
        url: p['url'], //仅为示例，并非真实的接口地址
        data: p['param'],
        method: method,
        // header: {
        //    'Content-Type': 'application/json'
        // },
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },  
        success: function(res) {
          typeof(cbf)=="function"?cbf(res.data):"";
         // wx.hideToast();
          wx.hideNavigationBarLoading();
        }
    })
 },
 //页面的数据 
  //页面的数据 
  setPageData: function (pageName, data = {}) {
    var curData = this.pageData[pageName] ? this.pageData[pageName] : {};
    // console.log("setPageData",data);
    for (var i in data) {
      //console.log("i", i, data[i]);
      curData[i] = data[i];
    }

    this.pageData[pageName] = curData;
    console.log(this.pageData);
  },
  getPageData: function (pageName, key = '') {
    var curData = this.pageData[pageName];
    if (key) {
      return curData ? curData[key] : null;
    } else {
      return curData;
    }
  },
  //上传图片
 upload: function (filePath, suc) {
   var that = this;
   wx.showToast({
     title: '上传中...',
     icon: 'loading',
     duration: 5000
   });
   qiniuUploader.upload(filePath, (res) => {
     // that.setData({
     //   'imageURL': res.imageURL,
     // });
     wx.hideToast();
     suc ? suc(res) : '';
   }, (error) => {
     console.log('error: ' + error);
     that.alert(JSON.stringify(error));
   }, {
       region: 'ECN', // 华东区
       uploadURL: 'https://up.qiniup.com',
       domain: this.data.qiniuUrl,
       uptokenURL: this.data.apiHost+'/api/upload/uptoken',
     })

 },
  alert:function(content){
    wx.showModal({
      title: '提示',
      content: content,
      showCancel:false,
    })
  },
   onLaunch: function (options) {
     //建connectSocket
   //  this.connectSocket();
     //console.log(options);
    // Do something initial when launch.
    var that = this;
     this.window();
     
     this.getUserInfo(function (userInfo) {
       console.log(userInfo);
       wx.setStorageSync("user_info", userInfo);
      // that.getNoti()//用户消息提醒
     });
    
  },
  //提醒小红点
   setRedDot:function(){
     if (wx.showTabBarRedDot) {
       wx.showTabBarRedDot({
         index: 3,
       });
     }else{
      //  wx.setNavigationBarTitle({
      //    title: '您有未读消息...'
      //  });
       //this.alert("您有未读消息,请到我的用户中心查看");
      
     }
   },
   clearRedDot: function () {
     if (wx.hideTabBarRedDot) {
        wx.hideTabBarRedDot({
          index: 3,
        });
     }else{

     }
   },
   
   getNoti:function(){
     var that = this;
     this.api("api/user/info", {}, function (res) {
       if (res.code != 200) {
         app.alert(res.msg);
         return;
       }
       if (res.data.allNoti>0){
         that.setRedDot();
       }
     })   
     
   },
   sendSocketMessage:function(data){
     var data = JSON.stringify(data);
     console.log("send:",data);
     if (this.data.socketOpen === false) {
       this.data.socketMsgQueue.push(data);
     }else{
       wx.sendSocketMessage({
         data: data
       });
     }
   },

  revMessage(k,fn){
    this.data.socketRevQueue[k] = fn;
  },
   
  //connectSocket
   connectSocket:function(data){
     var that =this;
     wx.connectSocket({
       url: this.data.websocket
     });
     wx.onSocketOpen(function (res) {
       console.log('onSocketOpen');
       that.data.socketOpen = true
       console.log(that.data.socketMsgQueue);
       for (var i = 0; i < that.data.socketMsgQueue.length; i++) {
         wx.sendSocketMessage({
           data: that.data.socketMsgQueue[i]
         });
       }
       that.data.socketMsgQueue = []
     })

     wx.onSocketMessage(function (r) {
       var res = JSON.parse (r.data);
       var key = res.dosometing;
       //判断页面是否打开中,聊天页面没有打开，那么消息提醒 
       var chatShow = that.getPageData("user/chat", 'show');
       if (key == "chatMessage" && chatShow==0){
         that.api("message/incMessagesCount",{
           f_user_id: res.user.user_id
         });
         return ;
       }
       //执行dosometing
       if (key && that.data.socketRevQueue[key] && typeof (that.data.socketRevQueue[key])=="function"){
         that.data.socketRevQueue[key](res);
       }
      
      // console.log('收到服务器内容：', res);
     })
     var that = this;
     wx.onSocketError(function (res) {

      // that.alert('WebSocket连接打开失败，请检查！');
       console.log(res)
     })
     wx.onSocketClose(function (res) {
       console.log('WebSocket 已关闭！')
     })
   },
   thumb_up:function(topic_id,suc,fail){//点赞
     this.api('topic/thumb_up', {
       topic_id: topic_id,
       method: 'POST',
     }, function (res) {
       if (res.code != 200) {
         fail ? fail(res):'';
         app.alert(res.msg);
         return;
       }
       suc ? suc(res.data):'';
     });
   },
   in_array: function (search, array) {
     for (var i in array) {
       if (array[i] == search) {
         return i;
       }
     } 
     return false;
   },
   DateDiff(sDate1, sDate2) {    //sDate1和sDate2是2006-12-18格式    
     var day1 = new Date(sDate1);
     var day2 = new Date(sDate2);
     return Math.floor((day2 - day1) / (1000 * 60 * 60 * 24));
     //   return  iDays + 1
   },
   date(i=0){
     var now = new Date();
     now.setDate(now.getDate() + i);
     var m = Number(now.getMonth()) + 1;
     var d = Number(now.getDate());
     if (m < 10) {
       m = "0" + m;
     }
     if (d < 10) {
       d = "0" + d;
     }
     return now.getFullYear() + "-" + m + "-" + d;
   },
   
})